package com.share.example.spider.utils;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.WebClient;

import java.util.HashMap;
import java.util.Map;

public class WebClientUtil {
    private static Map<String, WebClient> map = new HashMap<>();

    public static WebClient getWebClient(String name) {
        WebClient driver = map.get(name);
        if (driver != null) {
            return driver;
        } else {
            synchronized (name) {
                WebClient dri = map.get(name);
                if (dri != null) {
                    return dri;
                }

                WebClient webClient = new WebClient(BrowserVersion.getDefault());//创建火狐浏览器 2.23版本是FIREFOX_45 new不写参数是默认浏览器
                webClient.getOptions().setCssEnabled(false);//（屏蔽)css 因为css并不影响我们抓取数据 反而影响网页渲染效率
                webClient.getOptions().setThrowExceptionOnScriptError(false);//（屏蔽)异常
                webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);//（屏蔽)日志
                webClient.getOptions().setJavaScriptEnabled(true);//加载js脚本
                webClient.getOptions().setTimeout(5000);//设置超时时间
                webClient.setAjaxController(new NicelyResynchronizingAjaxController());//设置ajax
                map.put(name, webClient);
                return webClient;
            }
        }
    }
}
